import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import type { State } from '../index'

import { useCookies } from '@vueuse/integrations/useCookies';
const cookies = useCookies()
interface User {
  [index: string]: unknown
}
/**
 * id
 * pid 父id
 * permissionName 目录名称user,role等
 * displayName 显示名称，用户管理，角色管理等
 * description 描述
 * menuFlag 是否在目录中显示
 * orderNumber 同级目录顺序号
 * operation 操作属性,查看是必须的，0只有查看权限，1增加，2修改，
 * 4删除，3增加修改，5增加删除，6修改删除，7增加修改删除
 * children 子目录列表
 */
interface Permission {
  id: number;
  pid?:number;
  permissionName:string;
  displayName:string;
  description?:string;
  menuFlag?:number;
  orderNumber:number;
  operation:number;
  children?:Array<Permission>
}

/**
 * token
 * user用户数据
 * permission该用户获得权限目录
 * refreshToken 刷新token需要的token
 * canRefresh 能否刷新token的变量，如果一直有对后端的请求就为true,在utils的http.ts和login的Login.vue中可看到使用
 */
export interface UsersState {
  token: string
  user: User
  permission:Permission[]
  refreshToken:string
  canRefresh:boolean
}

const state: UsersState = {
  token: cookies.get("token"),
  user: cookies.get("user"),
  permission:cookies.get("permission"),
  refreshToken:cookies.get("refreshToken"),
  canRefresh:false
};

const mutations: MutationTree<UsersState> = {
  updateToken(state, payload){
    state.token = payload;
    cookies.set("token", payload);
  },
  updateUserInfo(state, payload){
    state.user = payload;
    cookies.set("user", payload);
  },
  updatePermission(state, payload){
    state.permission = payload;
    cookies.set("permission", payload);
  },
  updateRefreshToken(state, payload){
    state.refreshToken = payload;
    cookies.set("refreshToken", payload);
  }, 
  updateCanRefresh(state, payload){
    state.canRefresh = payload;
  }, 
  clearToken(state){
    state.token = '';
    cookies.set("token", '');
  }
};
const actions: ActionTree<UsersState, State> = {
  // login(context, payload){
  //   console.log('login')
  //   //return http.post('/users/login', payload)
  // },
  // infos(){
  //   return http.get('/users/infos')
  // }
};
const getters: GetterTree<UsersState, State> = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}